package com.zb777.shuzhilingxi.service.impl;


import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zb777.shuzhilingxi.Pojo.dto.MistakenQuestionDTO;
import com.zb777.shuzhilingxi.Pojo.entity.MistakenQuestion;
import com.zb777.shuzhilingxi.Pojo.entity.MistakenQuestionList;
import com.zb777.shuzhilingxi.mapper.MistakenQuestionMapper;
import com.zb777.shuzhilingxi.result.Result;
import com.zb777.shuzhilingxi.service.IMistakenQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb777.shuzhilingxi.utils.AliOssUtil;
import com.zb777.shuzhilingxi.utils.LlamaConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author redaiyu
 * @since 2025-07-12
 */
@Service
@Slf4j
public class MistakenQuestionServiceImpl extends ServiceImpl<MistakenQuestionMapper, MistakenQuestion> implements IMistakenQuestionService {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private LlamaConfig llamaConfig;
    @Override
    @Transactional
    public Result saveMistakenQuestion(MistakenQuestionDTO mistakenQuestionDTO) {
        String imageurl = null;
        if (mistakenQuestionDTO.getImage() != null && !mistakenQuestionDTO.getImage().isEmpty()) {
            log.info("上传图片");
            imageurl = aliOssUtil.processBase64Upload(mistakenQuestionDTO.getImage());
        }
        String text="";
        try {
            text = llamaConfig.simpleMultiModalConversationCall(imageurl, "识别图中的文字和数字");
        } catch (NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e);
        }
        log.info("图片描述：{}", text);
        MistakenQuestion mistakenQuestion = new MistakenQuestion()
                .setQuestionListId(mistakenQuestionDTO.getListId())
                .setContent(mistakenQuestionDTO.getContent())
                .setImage(imageurl)
                .setIsImage(mistakenQuestionDTO.getIsImage())
                .setCreatedAt(LocalDateTime.now())
                .setImageDescribe(text)
                .setIsDeleted( false);


        log.info("保存的错题：{}", mistakenQuestion);
        MistakenQuestionList one = Db.lambdaQuery(MistakenQuestionList.class).eq(MistakenQuestionList::getListId, mistakenQuestionDTO.getListId()).one();
        Db.lambdaUpdate(MistakenQuestionList.class)
                .set(MistakenQuestionList::getCount, one.getCount()+1)
                .eq(MistakenQuestionList::getListId, mistakenQuestionDTO.getListId())
                .update();
        save(mistakenQuestion);
        return Result.success("添加成功", mistakenQuestion.getQuestionId());
    }

    @Override
    public Result<List<MistakenQuestion>> selectMistakenQuestion(Integer listId) {
        List<MistakenQuestion> list = lambdaQuery().eq(MistakenQuestion::getQuestionListId, listId)
                .eq(MistakenQuestion::getIsDeleted, false)
                .list();
        if (list == null||list.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        return Result.success(list);
    }

    @Override
    @Transactional
    public Result deleteMistakenQuestion(Integer questionId) {

        MistakenQuestion mistakenQuestion = lambdaQuery()
                .eq(MistakenQuestion::getQuestionId, questionId)
                .one();
        MistakenQuestionList mistakenQuestionList = Db.lambdaQuery(MistakenQuestionList.class)
                .eq(MistakenQuestionList::getListId, mistakenQuestion.getQuestionListId())
                .one();
        lambdaUpdate().set(MistakenQuestion::getIsDeleted, true)
                .eq(MistakenQuestion::getQuestionId, questionId)
                .update();

        Db.lambdaUpdate(MistakenQuestionList.class)
                .set(MistakenQuestionList::getCount,mistakenQuestionList.getCount()-1)
                .eq(MistakenQuestionList::getListId, mistakenQuestion.getQuestionListId())
                .update();
        return Result.success("删除成功");
    }

    @Override
    public Result updateMistakenQuestion(Integer questionId, MistakenQuestion mistakenQuestion) {

        MistakenQuestion m = lambdaQuery().eq(MistakenQuestion::getQuestionId, questionId).one();
        m.setContent(mistakenQuestion.getContent());
        if (mistakenQuestion.getIsImage()){
            m.setIsImage(true);
            m.setImage(aliOssUtil.processBase64Upload(mistakenQuestion.getImage()));
        }else{
            m.setIsImage(false);
              m.setImage("");
        }
        lambdaUpdate().eq(MistakenQuestion::getQuestionId, questionId)
                .update(m);
        return Result.success("修改成功");
    }

    @Override
    public Flux<String> updateMistakenQuestionAnswer(Integer questionId) {
        MistakenQuestion mistakenQuestion = lambdaQuery().eq(MistakenQuestion::getQuestionId, questionId).one();
        String text="";
        try {
            text = llamaConfig.simpleMultiModalConversationCall(mistakenQuestion.getImage(), "生成图中的题目答案解析");
        }catch (NoApiKeyException | UploadFileException e){
            e.printStackTrace();
        }
        String finalText = text;
        lambdaUpdate().eq(MistakenQuestion::getQuestionId, questionId)
                .set(MistakenQuestion::getAnswer, finalText)
                .update();
        Flux<String> flux = Flux.create(sink -> {
            sink.next(finalText);
        });

        return flux;
    }


}
